package server;

import net.sf.json.JSONObject;
import util.Hash;

import java.util.UUID;

/**
 * User: tum0r
 * Package Name: server
 * Time: 2019-03-11 Monday 15:59:56
 */
public class RegisterServer extends BaseServer {
    public boolean checkRegister(String username) {
        return sql.query("select * from user where username=?", new Object[]{username}).size() == 0;
    }

    public JSONObject register(String username, String password, String again, String cookie, String verificationCode) {
        JSONObject result = JSONObject.fromObject("{}");
        result.put("state", "false");
        result.put("content", "注册失败，原因未知");
        VerificationCodeServer verificationCodeServer = new VerificationCodeServer();
        verificationCodeServer.open();
        if (verificationCodeServer.checkVerificationCode(cookie, verificationCode)) {
            if (password.equals(again)) {
                if (checkRegister(username)) {
                    Hash hash = new Hash();
                    String uuid = UUID.randomUUID().toString();
                    if (sql.update("insert into user(uuid, username, password, icon, type, last_language, state) value(?, ?, ?, ?, ?, ?, ?)", new Object[]{uuid, username, hash.passwordEncryption(password), "{}", 0, "Java", 1}) == 1) {
                        result.put("userID", uuid);
                        result.replace("state", "true");
                        result.replace("content", "注册成功，<br><br>用户名:&nbsp;&nbsp;" + username + "<br><br>密码:&nbsp;&nbsp;" + password);
                    }
                } else {
                    result.replace("content", "注册失败，用户名 " + username + " 已被注册");
                }
            } else {
                result.replace("content", "注册失败，两次密码输入不一致");
            }
        } else {
            result.replace("content", "注册失败，验证码不正确");
        }

        return result;
    }
}
